package com.damage.business_dept.service.impl;

import com.damage.business_dept.mapper.ISupplierMapper;
import com.damage.business_dept.service.ISupplierService;
import com.damage.common.config.SupplierConfig;
import com.damage.common.entity.Supplier;
import com.damage.common.exception.UniqueException;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import org.activiti.engine.IdentityService;
import org.activiti.engine.identity.Group;
import org.activiti.engine.identity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SupplierServiceImpl implements ISupplierService{

    @Autowired
    private ISupplierMapper mapper;

    @Autowired
    private IdentityService identityService;

    @Autowired
    private SupplierConfig supplierConfig;

    @Value("${pageSize}")
    private Integer pageSize;

    @Override
    @Transactional
    public Integer newSupplier(Supplier supplier)
            throws UniqueException{
        Supplier sqlSupplier = mapper.findByName(supplier.getName());
        if (sqlSupplier != null){
            //供应商的名字已存在
            throw new UniqueException("供应商的名字已经存在！");
        }
        //插入一个新的供应商到数据库
        Integer result = mapper.insert(supplier);
        //检查并添加为activiti的用户
        String userId = getActivitiUserId(supplier.getId());
        List<User> users = identityService.createUserQuery().userId(userId).list();
        if (users.size() == 1) {
            //如果已经存在该用户，就更新用户的信息
            User user = users.get(0);
            user.setFirstName(supplier.getName());
            user.setPassword(supplier.getPassword());
            identityService.saveUser(user);

            //删除存在用户的membership
            List<Group> groups = identityService.createGroupQuery().groupMember(userId).list();
            for (Group group : groups) {
                identityService.deleteMembership(userId, group.getId());
            }

            //添加新的membership
            identityService.createMembership(userId, SupplierConfig.group);
        } else {
            //是新的用户
            User user = identityService.newUser(userId);
            user.setFirstName(supplier.getName());
            user.setPassword(supplier.getPassword());
            identityService.saveUser(user);
            //添加membership
            identityService.createMembership(userId, SupplierConfig.group);
        }
        return result;
    }

    @Override
    public PageInfo<Supplier> findAll(Integer pageNum) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Supplier> pageInfo = new PageInfo<>(mapper.findAll());
        return pageInfo;
    }

    @Override
    public PageInfo<Supplier> findSupplier(Integer pageNum, String name) {
        if (pageNum == null) {
            pageNum = 1;
        }
        PageHelper.startPage(pageNum,pageSize);
        PageInfo<Supplier> pageInfo = new PageInfo<>(mapper.findLikeName(name));
        return pageInfo;
    }

    @Override
    public Supplier findById(Integer id) {
        return mapper.findById(id);
    }

    @Override
    @Transactional
    public Integer update(Supplier supplier) {
        //更新供应商
        Integer result = mapper.update(supplier);
        //更新activiti相应的记录
        String userId = getActivitiUserId(supplier.getId());
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null){
            //修改名字
            String name = supplier.getName();
            if (!Strings.isNullOrEmpty(name)){
                user.setFirstName(name);
            }
            //修改密码
            String password = supplier.getPassword();
            if (!Strings.isNullOrEmpty(password)){
                user.setPassword(password);
            }
            identityService.saveUser(user);
        }
        return result;
    }

    @Override
    @Transactional
    public Integer deleteById(Integer id) {
        //删除供应商
        Integer result = mapper.deleteById(id);
        //删除activiti相应的记录
        String userId = getActivitiUserId(id);
        User user = identityService.createUserQuery().userId(userId).singleResult();
        if (user != null){
            identityService.deleteUser(user.getId());

        }
        return result;
    }

    //通过实体类id,获得相应Activiti的用户id
    private String getActivitiUserId(Integer id){
        StringBuffer sb = new StringBuffer("supplier:");
        sb.append(id);
        String userId = sb.toString();
        return userId;
    }
}
